/**
 * Copyright (c) 2016,http://www.365wuliu.com/  All Rights Reserved.
 */
package com.cargo.base.file;

import com.cargo.base.constants.CommonConsts;
import com.cargo.base.utils.CheckUtil;

import java.io.*;

/** 
 * FileProcessor:文件流处理类
 * @Project Name:edi 
 * @File Name:FileProcessor.java 
 * @Package Name:com.cargo.base.file
 * @Creator:wizard
 * @Date:2017年11月3日下午3:30:18
 */
public class FileProcessor {
	
	/**
	 * 
	 * string2File:将字符串内容写入指定文件
	 * @param content
	 * @param filePath
	 * @param charset
	 * @return 
	 * @return :boolean 
	 * @Creator:wizard
	 * @Date:2016年11月3日 下午4:03:34
	 */
	public static boolean string2File(String content, String filePath, String charset) {
		boolean flag = true;
		//定义文件及输入输出流
		File file = null;
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			//待生成文件
			file = new File(filePath);
			if(!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			//设置文件写入的字符集
			if(!CheckUtil.isNotEmpty(charset)) {
				charset = CommonConsts.CHARSET_UTF8;
			}
			//初始化输入输出流
			reader = new BufferedReader(new StringReader(content));
			writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset));
			//定义字符缓冲区
			char buf[] = new char[1024];
			int length;
			while((length = reader.read(buf)) != -1) {
				writer.write(buf, 0, length);
			}
			//关闭输入输出流
			writer.flush();
			reader.close();
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		} finally {
			if(reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return flag;
	}
	
	/**
	 * 
	 * string2InputStream:字符串内容转化为输入流
	 * @param content
	 * @param charset
	 * @return 
	 * @return :InputStream 
	 * @Creator:wizard
	 * @Date:2016年11月3日 下午4:23:08
	 */
	public static InputStream string2InputStream(String content, String charset) {
		//定义输入流
		InputStream inputStream = null;
		//设置字符集
		if(!CheckUtil.isNotEmpty(charset)) {
			charset = CommonConsts.CHARSET_UTF8;
		}
		
		try {
			//初始化输入流数据
			inputStream = new ByteArrayInputStream(content.getBytes(charset));
			//关闭输入流
			inputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(inputStream != null) {
				try {
					//关闭输入流
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return inputStream;
	}
	
	public static void main(String[] args) {
		String content = "1234567890\r\n"
				+ "abcdefg\r\n"
				+ "输入一行汉字";
		String path = "E:\\Temp\\testString2File.txt";
		String charset = "GBK";
		boolean flag = string2File(content, path, charset);
		System.out.println(flag);
		
	}
}
